package org.vincent.esDemo;

import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.querydsl.QPageRequest;
import org.springframework.stereotype.Component;
import org.vincent.esDemo.model.Book;

import java.util.List;


@Component
public class ESOperation implements InitializingBean {

    @Autowired
    private ElasticsearchTemplate template;

    @Override
    public void afterPropertiesSet() throws Exception {
        // match
        QueryBuilder query = QueryBuilders.matchAllQuery();

        // filter
        BoolQueryBuilder filter = QueryBuilders.boolQuery();
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("published").gte(2000);
        filter.must(rangeQueryBuilder);

        String[] fields = new String[]{"title", "published"};
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder()
                .withQuery(query)
                .withFilter(filter)
                .withFields(fields)
                .withPageable(new QPageRequest(0, 10));

        List<Book> books = template.queryForList(queryBuilder.build(), Book.class);
        System.out.println(books);
    }
}
